package com.maidada.mddaichat.common;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author: wulinxuan
 * @date: 2024/12/17 23:00
 */
public class ResultUtils<T> {

    public static <T> BaseResponse<T> success(T data) {
        return new BaseResponse<>(0, data, "success");
    }

    public static <T> BaseResponse<T> successWithMsg(String msg) {
        return new BaseResponse<>(0, null, msg);
    }

    public static <T> BaseResponse<T> error(ErrorCode errorCode) {
        return new BaseResponse<>(errorCode);
    }

    public static <T> BaseResponse<T> error(int code, String msg) {
        return new BaseResponse<>(code, null, msg);
    }

    public static <T> BaseResponse<T> error(ErrorCode errorCode, String msg) {
        return new BaseResponse<>(errorCode.getCode(), null, msg);
    }

    public static void setResponseError(HttpServletResponse response, Integer httpCode, ErrorCode errorCode) {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        BaseResponse<Object> result = ResultUtils.error(errorCode);
        OutputStream os;
        try {
            os = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");
            response.setStatus(httpCode);
            os.write(new ObjectMapper().writeValueAsString(result).getBytes("UTF-8"));
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}